/**
 * 
 */
package com.totobox.apps.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * @author ytslove
 *
 */
public class JSONParser {

	public JSONObject getJSONObject(String url){
		
		JSONParser parser = new JSONParser();
		return parser.parseObject(url , null);
	}

	public JSONObject getJSONObject(String url , String[] args){
		JSONParser parser = new JSONParser();
		return parser.parseObject(url , args);
	}
	
	public JSONArray getJSONArray(String url , String[] args){
		JSONParser parser = new JSONParser();
		return parser.parseArray(url , args);
	}
	
	
	public JSONObject parseObject(String url , String[] args){
		
		InputStream is = null;
		JSONObject jArray = null;
		
		//http post
	    try{
	    		url = this.strJoin(url , args);
	    		
	    		Log.e("json-url", url);
	    		
	            HttpClient httpclient = new DefaultHttpClient();
	            httpclient.getParams().setParameter("http.protocol.expect-continue", false);
	            httpclient.getParams().setParameter("http.connection.timeout", 20000);
	            httpclient.getParams().setParameter("http.socket.timeout", 20000);
	            
	            
	            HttpPost httppost = new HttpPost(url);
	            
	            HttpResponse response = httpclient.execute(httppost);
	            
	            StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == 200) {
					HttpEntity entity = response.getEntity();
					is = entity.getContent();
				}

	    }catch(Exception e){
	            Log.e("log_http", "Error in http connection "+e.toString());
	    }
	    
	    StringBuilder sb = new StringBuilder();
	    BufferedReader reader = null;
	    
	    try{
	    	
	    	String tmp = null;
	    	reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

	    	while ((tmp = reader.readLine()) != null) {
	    		sb.append(tmp + "\n");
	    	}
	            
	    }catch(Exception e){
	    	Log.e("log_tag > reader : ", "Error converting result "+e.toString());
	    }
	    finally{
	    	try{is.close();
	    	}catch(Exception e){}
	    	try{reader.close();
	    	}catch(Exception e){}
	    }
	    
	    try{
	    	Log.e("json-data", sb.toString());
            jArray = new JSONObject(sb.toString());
	    }catch(JSONException e){
	            Log.e("log_tag > parse : ", "Error parsing data "+e.toString());
	    }
    
	    return jArray;
	}
	
	public JSONArray parseArray(String url , String[] args){
		
		InputStream is = null;
		JSONArray jArray = null;
		
		//http post
	    try{
	    		url = this.strJoin(url , args);
	    		
	    		Log.e("json-url", url);
	    		
	    		HttpClient httpclient = new DefaultHttpClient();
	            httpclient.getParams().setParameter("http.protocol.expect-continue", false);
	            httpclient.getParams().setParameter("http.connection.timeout", 10000);
	            httpclient.getParams().setParameter("http.socket.timeout", 10000);
	            
	            HttpPost httppost = new HttpPost(url);
	            
	            HttpResponse response = httpclient.execute(httppost);
	            
	            StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == 200) {
					HttpEntity entity = response.getEntity();
					is = entity.getContent();
				}

	    }catch(Exception e){
	            Log.e("log_tag", "Error in http connection "+e.toString());
	    }
	    
	    StringBuilder sb = new StringBuilder();
	    BufferedReader reader = null;
	    
	    try{
	    	
	    	String tmp = null;
	    	reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

	    	while ((tmp = reader.readLine()) != null) {
	    		sb.append(tmp + "\n");
	    	}
	            
	    }catch(Exception e){
	    	Log.e("log_tag", "Error converting result "+e.toString());
	    }
	    finally{
	    	try{is.close();
	    	}catch(Exception e){}
	    	try{reader.close();
	    	}catch(Exception e){}
	    }
	    
	    try{
	    	Log.e("json-data", sb.toString());
            jArray = new JSONArray(sb.toString());            
	    }catch(JSONException e){
	            Log.e("log_tag", "Error parsing data "+e.toString());
	    }
    
	    return jArray;
	}

	/**
	 * 
	 * @param url
	 * @param args
	 * @return
	 */
	public String strJoin(String url , String[] args){
		if(url == null){
			return "";
		}
		else if(args == null || args.length == 0){
			return url;
		}
		else{
			return MessageFormat.format(url, args);
		}
	}
	
	public void Test(){
		
		/*ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

		JSONParser parser = new JSONParser();
		
        JSONObject json = parser.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo");
                */
        try{
        	
        	/*JSONArray  earthquakes = json.getJSONArray("earthquakes");
        	
	        for(int i=0;i<earthquakes.length();i++){						
				HashMap<String, String> map = new HashMap<String, String>();	
				JSONObject e = earthquakes.getJSONObject(i);
				
				map.put("id",  String.valueOf(i));
	        	map.put("name", "Earthquake name:" + e.getString("eqid"));
	        	map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
	        	mylist.add(map);			
			}		*/
	        
	        JSONArray jObj = new JSONArray("[{'bMemberCheck':0, 'bConfirmCheck':0,'tiMemberStatus':0,'vcMemberKey':'fgTh3DkFdfsdsf43343','vcName':'홍길동'}]");
	        
	        JSONObject e = jObj.getJSONObject(0);
	        
	        System.out.println( e.getString("bMemberCheck"));
	        System.out.println( e.getString("bConfirmCheck"));
	        System.out.println( e.getString("tiMemberStatus"));
	        System.out.println( e.getString("vcMemberKey"));
	        System.out.println( e.getString("vcName"));
	        
        }catch(JSONException e)        {
        	 Log.e("log_tag", "Error parsing data "+e.toString());
        }
	}
	
}
